package com.zero.cloud.gateway.logging;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;


/**
 * @author MARCH
 * @className AccessLogFilter
 * @description
 * @date 2025/6/3 21:50
 */
@Component
@Slf4j
public class AccessLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        addOriginalRequestUrl(exchange, req.getURI());
        String path = req.getURI().getRawPath();
        // 获取请求地址和URI
        String requestPath = exchange.getRequest().getPath().toString();
        int port = exchange.getRequest().getURI().getPort();
        if (path.length() <= 0) {
            return chain.filter(exchange);
        }
        String newPath = path.substring(path.substring(1).split("/")[0].length() + 1);
        if (port == 10000) {
            log.info("gateway 重写转发路径----原路径：{}，新路径：{}", path, newPath);
        }

        ServerHttpRequest request = req.mutate().path(newPath).build();
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
        ServerWebExchangeUtils.addOriginalRequestUrl(exchange, req.getURI());
        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());
        //重置clientID
//        String clientId = GatewayHelper.getClientId(exchange);
//        exchange.getAttributes().put(GatewayConstant.clientId, clientId);
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
